<template>
    <div class="login-container">
      <el-card class="box-card">
        <!--    面包屑导航-->
        <div slot="header" class="clearfix">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>品牌列表</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <!--    搜索栏和添加-->
        <div class="seachAdd">
          <el-form :inline="true" :model="query" class="demo-form-inline">
            <el-form-item>
              <el-input v-model="query.name" placeholder="请输入商品名称" @keyup.enter.native="getBrand"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getBrand" :loading="isGetting">查询</el-button>
            </el-form-item>
          </el-form>
          <el-button
            type="success"
            round
            size="mini"
            :disabled="isGetting"
            @click="dialogFormVisible = true"
          >
            添加品牌
          </el-button>
        </div>
      </el-card>
      <el-card class="box-card">
        <el-table
          :data="tableData"
          v-loading="isGetting"
          style="width: 100%">
          <el-table-column
            prop="chineseName"
            label="品牌中文名称"
          >
          </el-table-column>
          <el-table-column
            prop="englishName"
            label="品牌英文名称"
          >
          </el-table-column>
          <el-table-column
            label=""
          >
            <template slot-scope="scope">
              <el-image
                style="width: 150px; height: 80px"
                :src="scope.row.logo"
                lazy
              >
                <div slot="placeholder" class="image-slot">
                  加载中<span class="dot">...</span>
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column
            prop="letter"
            sortable
            label="品牌首字母">
          </el-table-column>
          <el-table-column
            prop="sourceAsMap.address"
            label="操作">
            <!-- 如果需要自定义表格列模板，则把需要自定义的内容放到 template 里面 -->
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="编辑品牌" placement="top-end">
                <el-button
                  size="mini"
                  circle
                  icon="el-icon-edit"
                  type="primary"
                  :loading="isAdding"
                  @click="onUpdate(scope.row.id)"
                ></el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除品牌" placement="top-end">
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  :loading="isDeleting"
                  @click="deleteBrand(scope.row.id)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!--    分页栏-->
      <el-pagination
        class="page"
        background
        layout="sizes,prev, pager, next"
        :page-sizes="[10, 15, 20]"
        :page-size.sync =query.size
        :current-page.sync = query.page
        @current-change = pageChange
        @size-change=pageChange
        :disabled = "isGetting"
        :total="total">
      </el-pagination>

<!--      品牌添加弹框-->
      <el-dialog
        :title= dialogName
        :visible.sync="dialogFormVisible"
        append-to-body
        @close="closeForm"
      >
        <el-form
          :model="form"
          :rules="formRules"
          ref="brandForm"
          label-width="120px"
          :disabled="isAdding || isEcho"
        >
          <el-form-item label="品牌中文名称" prop="chineseName">
            <el-input v-model="form.chineseName"></el-input>
          </el-form-item>
          <el-form-item label="品牌英文名称" prop="englishName">
            <el-input v-model="form.englishName"></el-input>
          </el-form-item>
          <el-form-item label="品牌首字母" prop="letter">
            <el-input v-model="form.letter"></el-input>
          </el-form-item>
          <el-form-item label="LOGO" prop="logo">
            <el-upload
              action="http://localhost:8001/api/file/upload"
              name="file"
              :headers=headers
              :on-remove="handleRemove"
              :file-list="fileList"
              multiple
              class="upload-demo"
              :on-success="handleSuccess"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过20M</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeForm">取 消</el-button>
          <el-button type="primary" @click="onSubmit" :loading="isAdding">确 定</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
import { searchBrandList, addBrand, getBrandById, updateBrand, deleteBrandById } from '@/api/brand'
import { deleteImage } from '@/api/image'
import { Message } from 'element-ui'
export default {
  name: 'BrandList',
  components: {},
  props: {},
  data () {
    return {
      query: { // 搜索请求参数
        page: 1,
        size: 10,
        name: ''
      },
      form: { // 添加/修改品牌表单
        chineseName: '', // 品牌中文名称
        englishName: '', // 品牌英文名称
        letter: '', // 品牌首字母
        logo: '' // 品牌logo
      },
      formRules: { // 表单验证规则
        chineseName: [
          {
            required: true,
            message: '请输入品牌中文名称',
            trigger: 'blur'
          },
          {
            max: 50,
            message: '长度最长是 50 个字符',
            trigger: 'blur'
          }
        ],
        englishName: [
          {
            required: true,
            message: '请输入品牌英文名称',
            trigger: 'blur'
          },
          {
            max: 50,
            message: '长度最长是 50 个字符',
            trigger: 'blur'
          }
        ],
        letter: [
          {
            required: true,
            message: '请输入品牌首字母',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 1,
            message: '长度只能是1个字符',
            trigger: 'blur'
          },
          {
            pattern: /^[A-Z]$/, message: '首字母必须是大写字母', trigger: 'blur'
          }
        ],
        logo: [
          {
            required: true,
            message: '请输入品牌图标',
            trigger: 'blur'
          }
        ]
      },
      tableData: [], // 品牌展示表格数组
      fileList: [], // 弹框表单图片回显数组
      dialogFormVisible: false, // 弹出框开关
      formLabelWidth: '120px', // 弹出表单宽度控制
      isAdding: false, // 添加品牌loading
      isGetting: false, // 获取品牌loading
      isEcho: false, // 表单回显开关
      isDeleting: false, // 删除品牌开关
      total: 0, // 总页数
      isEdit: false, // false为添加品牌 true为修改品牌
      dialogName: '添加表单', // 弹出框名称（添加品牌/修改品牌）
      brandId: 0 // 当前选中的品牌id
    }
  },
  computed: {
    headers () {
      return {
        Authorization: window.sessionStorage.getItem('accessToken').toString() // 直接从本地获取token就行
      }
    }
  },
  watch: {
    isEdit (newValue) {
      // 判断表单名称
      // newValue === true ? this.dialogName = '修改表单' : '添加表单'
      if (newValue) {
        this.dialogName = '修改表单'
      } else {
        this.dialogName = '添加表单'
      }
    }
  },
  created () {
    this.getBrand()
  },
  mounted () {
  },
  methods: {
    async getBrand () {
      // 开启loading
      this.isGetting = true
      await searchBrandList(this.query).then(resp => {
        // 获取成功
        if (resp.data.code === 20000) {
          this.total = resp.data.data.total
          this.tableData = resp.data.data.records
        } else {
          Message({
            type: 'warning',
            message: resp.data.message
          })
        }
      }).catch(() => {})
      // 关闭loading
      this.isGetting = false
    },
    pageChange () {
      // 页码改变触发
      this.getBrand()
    },
    handleRemove () {
      // 文件列表移除文件时的钩子
      deleteImage(this.fileList[0].url).then(resp => {
        // 获取成功
        if (resp.data.code === 20000) {
          this.fileList = []
          Message({
            type: 'success',
            message: resp.data.message
          })
        } else {
          Message({
            type: 'warning',
            message: resp.data.message
          })
        }
      }).catch(() => {})
    },
    handleSuccess (response, file) {
      // 文件上传成功钩子
      console.log('response', response)
      // this.fileList[0].name = file.name
      // this.fileList[0].url = response.data.url
      this.fileList.push({ name: file.name, url: response.data })
      this.form.logo = response.data
    },
    onSubmit () {
      // 点击提交触发
      // 表单验证
      // validate 方法是异步的
      this.$refs.brandForm.validate(valid => {
        // 如果表单验证失败，停止请求提交
        if (!valid) {
          return
        }
        // 提交表单 开启loading
        this.isAdding = true
        // 判断执行更新操作还是添加操作
        this.isEdit ? this.updateBrand() : this.addBrand()
      })
    },
    addBrand () {
      addBrand(this.form).then(resp => {
        // 添加品牌
        if (resp.data.code === 20000) {
          // 清理弹框
          this.closeForm()
          // 告知修改成功
          Message({
            type: 'success',
            message: '添加成功'
          })
          // 刷新品牌列表
          this.getBrand()
        } else {
          Message({
            type: 'warning',
            message: resp.data.message
          })
        }
      }).catch(() => {})
    },
    async onUpdate (brandId) {
      // 打开回显开关
      this.isEcho = true
      // 修改弹出框名称
      this.isEdit = true
      // 打开弹出框开关
      this.dialogFormVisible = true
      // 更新选中品牌id
      this.brandId = brandId
      // 根据id查询品牌
      await getBrandById(brandId).then(resp => {
        // 添加品牌
        if (resp.data.code === 20000) {
          // 信息回显
          this.form = resp.data.data
          // this.form.name = resp.data.data.name === null ? '' : resp.data.data.name
          // this.form.letter = resp.data.data.letter === null ? '' : resp.data.data.letter
          // this.form.logo = resp.data.data.logo === null ? '' : resp.data.data.logo
          // 获取图片名称
          if (this.form.logo !== null) {
            const nameList = this.form.logo.split('/')
            this.fileList.push({ name: nameList[nameList.length - 1], url: this.form.logo })
          }
        } else {
          Message({
            type: 'warning',
            message: resp.data.message
          })
        }
      }).catch(() => {})
      // 关闭回显开关
      this.isEcho = false
    },
    async updateBrand () {
      await updateBrand(this.brandId, this.form).then(resp => {
        // 更新品牌
        if (resp.data.code === 20000) {
          // 清空弹框数据
          this.closeForm()
          // 刷新品牌列表
          this.getBrand()
          // 告知修改成功
          Message({
            type: 'success',
            message: '修改成功'
          })
        } else {
          Message({
            type: 'warning',
            message: resp.data.message
          })
        }
      }).catch(() => {})
    },
    async deleteBrand (id) {
      // 打开loading
      this.isDeleting = true
      await deleteBrandById(id).then(resp => {
        // 删除品牌
        if (resp.data.code === 20000) {
          // 清空弹框数据
          this.closeForm()
          // 刷新品牌列表
          this.getBrand()
          // 告知删除成功
          Message({
            type: 'success',
            message: '删除成功'
          })
        } else {
          Message({
            type: 'warning',
            message: resp.data.message
          })
        }
      }).catch(() => {})
      // 关闭loading
      this.isDeleting = false
    },
    closeForm () {
      // 关闭弹窗
      this.dialogFormVisible = false
      // 清空数据
      this.form.name = ''
      this.form.logo = ''
      this.form.letter = ''
      this.fileList = []
      // 清空表单验证信息
      if (this.$refs.brandForm !== undefined) {
        this.$refs.brandForm.resetFields()
      }
      // 清空选中品牌id
      this.brandId = 0
      // 关闭所有loading
      this.isAdding = false
      this.isEcho = false
      this.isDeleting = false
      this.isGetting = false
      this.isEdit = false
    }
  }
}
</script>

<style scoped lang="less">
  .box-card {
    width: 100%;
    margin-bottom: 10px;
  }
  .page {
    float: right;
  }
  .seachAdd {
    height: 35px;
    display: flex;
    justify-content: space-between;
  }
</style>
